function check_settings(){
	var tmp = (!(((viewer_settings & 2) != 2) || ((viewer_settings & 8) != 8)));
	return tmp;
}

(function ($) {
	$.extend($.browser, {
	    flash: (function () {
	        var found = false;
			try {
				new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				found = true;
			} catch(e) {
				$.each(navigator.plugins, function () {
					if (this.name.match(/flash/gim)) {
						found = true;
						return false;
					}
				});
			}
			return found;
	    })()
	});
})(jQuery);


$(document).ready(function(){

	$('.button_blue').bind('mouseenter', function(event) {
		$(this).fadeTo('fast', '0.8');
	});
	$('.button_blue').bind('mouseleave', function(event) {
		$(this).fadeTo('fast', '1');
	});
	$('.button_gray').bind('mouseenter', function(event) {
		$(this).fadeTo('fast', '0.8');
	});
	$('.button_gray').bind('mouseleave', function(event) {
		$(this).fadeTo('fast', '1');
	});
	$('#shuffle').bind('mouseenter', function(event) {
		$('#hint_shuffle').show();
	});
	$('#shuffle').bind('mouseleave', function(event) {
		$('#hint_shuffle').hide();
	});
	$('#repeat').bind('mouseenter', function(event) {
		$('#hint_repeat').show();
	});
	$('#repeat').bind('mouseleave', function(event) {
		$('#hint_repeat').hide();
	});
	$('#liketrack').bind('mouseenter', function(event) {
		$('#hint_like').show();
	});
	$('#liketrack').bind('mouseleave', function(event) {
		$('#hint_like').hide();
	});
	$('#disliketrack').bind('mouseenter', function(event) {
		$('#hint_dislike').show();
	});
	$('#disliketrack').bind('mouseleave', function(event) {
		$('#hint_dislike').hide();
	});
	$('#addtrack').bind('mouseenter', function(event) {
		$('#hint_add').show();
	});
	$('#addtrack').bind('mouseleave', function(event) {
		$('#hint_add').hide();
	});
	$('#savetrack').bind('mouseenter', function(event) {
		$('#hint_save').show();
	});
	$('#savetrack').bind('mouseleave', function(event) {
		$('#hint_save').hide();
	});
	$('input#searchartist').bind('blur', function(event, ui){
		var target = jQuery('input#searchartist');
		if ((target.val() == '') || (target.val() == 'Исполнитель')){
			target.addClass('input_info');

		}
	});
	$('input#searchartist').bind('focus', function(event, ui){
		var target = jQuery('input#searchartist'); 
		target.removeClass('input_info');
	});
	$('input#searchtrack').bind('blur', function(event, ui){
		var target = jQuery('input#searchtrack');
		if ((target.val() == '') || (target.val() == 'Композиция')){
			target.addClass('input_info');
		}
	});
	$('input#searchtrack').bind('focus', function(event, ui){
		var target = jQuery('input#searchtrack'); 
		target.removeClass('input_info');
	});

	// ИНИЦИАЛИЗАЦИЯ ПЛЕЕРА
	var Playlist = function(instance, playlist, options) {
		var self = this;

		this.instance = instance; // String: To associate specific HTML with this playlist
		this.playlist = playlist; // Array of Objects: The playlist
		this.options = options; // Object: The jPlayer constructor options for this playlist

		this.current = 0;

		this.cssId = {
			jPlayer: "jquery_jplayer_",
			interface: "jp_interface_",
			playlist: "jp_playlist_"
		};
		this.cssSelector = {};

		$.each(this.cssId, function(entity, id) {
			self.cssSelector[entity] = "#" + id + self.instance;
		});

		if(!this.options.cssSelectorAncestor) {
			this.options.cssSelectorAncestor = this.cssSelector.interface;
		}

		$(this.cssSelector.jPlayer).jPlayer(this.options);

		$(this.cssSelector.interface + " .jp-previous").click(function() {

			load_track('prev','manual');
			$(this).blur();

			return false;
		});

		$(this.cssSelector.interface + " .jp-next").click(function() {
			
			load_track('next','manual');
			$(this).blur();

			return false;
		});
	};

	var audioPlaylist = new Playlist("2", [] , {ready: function() {},supplied: "mp3", solution: "flash, html"});
	$("#jquery_jplayer_2").bind($.jPlayer.event.ended, function(event) { 
		load_track('next','auto');
	});

	$("#jquery_jplayer_2").bind($.jPlayer.event.volumechange , function(event) { 
		volume = event.jPlayer.status.volume;
	});
	$("#jquery_jplayer_2").bind($.jPlayer.event.error, function(event) { 
		 switch(event.jPlayer.error.type) {
			case $.jPlayer.error.URL:
				load_track('next','manual');
			break;
			case $.jPlayer.error.URL_NOT_SET:
				if (tracks.length > 0)
				{
					load_track('next','manual');
				}
			break;
		  }

	});

	VK._apiId = 2113983;
	VK.init(function() {
		if(!$.browser.flash){
			$("#flasherror").show();
			return;
		}
		init();
        VK.Widgets.Like("vk_like", {
            type: "button",
            width: "350",
            pageTitle: '► Меломания - приложение для настоящих любителей музыки.',
            pageUrl: 'http://vkontakte.ru/app2113983',
            tooltipPos: 'top',
            pageDescription: "Персональное радио. Плеер музыки со страниц пользователей. Самая популярная музыка Контакта. Отслеживание музыкальных тенденций. Поиск людей со схожими плейлистами."}, 5);
	});
});

function init(){
	if (!inited)
	{

		loadfriends(); //Сразу после загрузки страницы, вставляем юзерей в правое меню
		$('span#you').html(viewer_last_name+" "+viewer_first_name);
		$('div#you_tracks').html("<a href='#__JSNotWork' onclick='loadtracks("+viewer_id+", \""+viewer_last_name+" "+viewer_first_name+"\")'>"+viewer_last_name+" "+viewer_first_name+"</a>");
		$('div#you_radio').html("<a href='#__JSNotWork' onclick='loadradio("+viewer_id+", \""+viewer_last_name+" "+viewer_first_name+"\")'>"+viewer_last_name+" "+viewer_first_name+"</a>");
		if (send_tracklist == '1')
		{
			send_tracklist_func(viewer_id); //Если нужно, отсылаем треклист
		}

		inited = true;
	}
}



function send_tracklist_func(user_id){

	if (cache_audioget[user_id] !== undefined)
	{
			var tmp = '';
			for (var key in cache_audioget[user_id]) {
				var val = cache_audioget[user_id][key];
				tmp = tmp + val.title + "||" + val.artist + "||"+ val.aid+"##" ;	
			}

			var dataString = 'viewer_id='+ user_id + '&sig='+sig+'&tracklist='+encodeURIComponent(tmp);
			$.ajax({
			type: "POST",
			url: "/ajax_load_tracklist.php",
			data: dataString,
			cache: false,
			beforeSend: function(html)
			{
			},
			success: function(html){
			}
			});

	}else{
		VK.api("audio.get", {uid:user_id}, function(data) {

			cache_audioget[user_id] = data.response;

			var tmp = '';
			for (var key in data.response) {
				var val = data.response[key];
				tmp = tmp + val.title + "||" + val.artist + "||"+ val.aid+"##" ;   
			}

			var dataString = 'viewer_id='+ user_id + '&sig='+sig+'&tracklist='+encodeURIComponent(tmp);
			$.ajax({
			type: "POST",
			url: "/ajax_load_tracklist.php",
			data: dataString,
			cache: false,
			beforeSend: function(html)
			{
			},
			success: function(html){
			}
			});
		});	
	}

}

var stop_loading_dj = false;

function toggle_menu(menuid){

	stop_loading_dj = true

	//Убираем выделение с предыдущей вкладки
	$("#track"+mode+current_track+" li").removeClass("track_selected");

	var i=0;
	for (i=1;i<=6;i=i+1){
		$("td#menu"+i).removeClass("menu_a");
		$("td#menu"+i).addClass("menu");
	}

	$("td#menu"+i).removeClass("menu");
	$("td#menu"+menuid).addClass("menu_a");
		
	for (i=0;i<=6;i=i+1){
		$("div#cont"+i).hide();
	}

	$("div#cont"+menuid).show();

	if (menuid == 1){
		mode = 'dj';
		hide_editform();
		load_artistlist();
		hide_djtracks();
		tracks = [];
	}
	if (menuid == 2){
		mode = 'tracks';
		loadtracks(viewer_id, viewer_last_name+" "+viewer_first_name);
	}
	if (menuid == 3){
		mode = 'top';
		show_chartlist();
		tracks = [];
	}
	if (menuid == 4){
		mode = 'trends';
		load_trends();
	}
	if (menuid == 6){
		mode = 'search';
		tracks = [];
		$('#searchartist').val('Исполнитель');
		$('#searchtrack').val('Композиция');
		$('#searchtracklist').html('');
		$('input#searchartist').addClass('input_info');
		$('input#searchtrack').addClass('input_info');
		$('#content_search').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
		$('#search_more').html('');
	}

}

function loadfriends(){
	if (!(friends.length > 0)){
		$('#friendlist_'+mode).html('идет загрузка...');
		VK.api("friends.get", {uid:viewer_id, fields:"uid, first_name, last_name", count: 1000}, function(data) {

			for (var key in data.response) {
				var val = data.response[key];
				friends[friends.length] = [val.uid, val.last_name+" "+val.first_name];
			}
			friends.sort(sName);
			genfriendlist('tracks');
			$('#content_friends_radio').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
			$('#content_friends_tracks').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});

			toggle_menu(start_menu);
			$("#loader").hide();

		});
	}else{
		$('#content_friends_radio').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
		$('#content_friends_tracks').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
	}
}

function genfriendlist(nowmode){
	$('#friendlist_'+nowmode).html('');
	var keyword = '';
	keyword = $('#keyword_'+nowmode).val();
	if (keyword == 'Поиск...')
	{
	keyword = '';
	}
	var tmp = '';
	for (var key in friends) {
		var val = friends[key];

		if (keyword.length > 0)
		{
			if (stripos(' '+val[1], keyword) > 0)
			{
				tmp += "<div style='overflow: hidden; width: 130px; color: gray;'><nobr>• <a href='#__JSNotWork' title='"+val[1]+"' onclick='load"+nowmode+"("+val[0]+", \""+val[1]+"\");'>"+val[1]+"</a></nobr></div>";
			}
		}else{
			tmp += "<div style='overflow: hidden; width: 130px; color: gray;'><nobr>• <a href='#__JSNotWork' title='"+val[1]+"' onclick='load"+nowmode+"("+val[0]+", \""+val[1]+"\");'>"+val[1]+"</a></nobr></div>";
		}
	}	
	$("#friendlist_"+nowmode).html(tmp);
}

/*
function loadradio(uid,username){
		msgbox_show("В связи с техническими работами на сервере,<br>раздел Радио не будет работать до 18:00 (MSK).");
		return;
	if(!lock){
		lock = true;

		if (content_radio_loaded){
			$('#content_radio')[0].scrollTo(0);
		}		
		$('#radiolist').html("<div class=load_tracks><img src='/img/ajax_loader.gif' width=32 height=8></div>");
		$('#username_radio').html('Персональное радио пользователя <b>'+username+'</b>:<br>');

		//Подгружаем музыку пользователя
		if (cache_audioget[uid] !== undefined)
		{
			var tmp = '';
			var k = 1;
			for (var key in cache_audioget[uid]) {
				var val = cache_audioget[uid][key];
				tmp = tmp + val.title + "||" + val.artist + "||"+ val.aid+"##" ;   
				if(k == 20){
					break;
				}
				k++;
			}
			loadradio2(uid, tmp);
		}else{
			VK.api("audio.get", {uid:uid}, function(data) {

				cache_audioget[uid] = data.response;

				var tmp = '';
				var k = 1;
				for (var key in data.response) {
					var val = data.response[key];
					tmp = tmp + val.title + "||" + val.artist + "||"+ val.aid+"##" ; 
					if(k == 20){
						break;
					}
					k++;
				}		
				loadradio2(uid, tmp);
			});	
		}
	
	}
}
function loadradio2(uid, tracks20){

	var radiotracks = new Array();
	tracks = [];

	var dataString = 'user_id='+uid+'&tracks='+encodeURIComponent(tracks20);
	$.ajax({
	type: "POST",
	url: "/ajax_load_radio.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
	},
	success: function(html){
		$("#radiolist").html("");	
		var arr = explode('<br>', html);
		var tracktitle = '';
		for (var key in arr) {
			var val = arr[key];
			if (val.length > 0)
			{
					var arr2 = explode('|', val);					
					var artist = arr2[0];
					var track = arr2[1];
					var getaids = arr2[2];
					radiotracks[radiotracks.length] = [artist, track, getaids]; 
				}
		}


		
		
		var tmp = '';
			for (var key in radiotracks) {
				var val = radiotracks[key];
					var artist = val[0];
					var track = val[1];
					var getaids = val[2];

				tracks[key] = ['', artist, track, '', getaids];
				tracktitle = artist+ ' - ' + track;

				tmp += "<table class=track id='trackradio"+key+"' onclick='load_track("+key+",\"manual\");'><tr><td class=position_tracks>"+(key*1+1)+"</td><td title='"+tracktitle+"' class=artist_tracks><div>"+artist+"</div></td><td class=track_tracks title='"+tracktitle+"'><div>"+track+"</div></td></tr></table>";
			}
		if (radiotracks.length == 0)
		{
			$("#radiolist").html("<font color=red>Не хватает информации для построения плейлиста!</font><br><font color=gray>Если это ваше радио, отметьте композиции, которые вам нравится, в других плейлистах, а потом вернитесь в данный раздел.</font>");
		}else{
			$("#radiolist").html(tmp);
		}
			make_shuffle();		

			$('#content_radio').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
			content_radio_loaded = true;

			lock = false;
		}
	});
}
*/
function loadtracks(uid,username){

	if(!lock){
	lock = true;

	if (content_tracks_loaded){
		$('#content_tracks')[0].scrollTo(0);
	}
	$('#tracklist').html("<div class=load_tracks><img src='/img/ajax_loader.gif' width=32 height=8></div>");
	$('#username').html('Плейлист пользователя <b>'+username+'</b>:<br>');
	tracks = [];

	if (cache_audioget[uid] !== undefined)
	{
		setTimeout('loadtracks2('+uid+')', 400);
	}else{
		VK.api("audio.get", {uid:uid}, function(data) {
			cache_audioget[uid] = data.response;
			loadtracks2(uid);
		}); 
	}
	
	}
}

function loadtracks2(uid){
	$('#tracklist').html('');
			
	if (cache_audioget[uid].length > 0)
	{

		var tracktitle = '';
		var tmp = '';
		for (var key in cache_audioget[uid]) {
			var val = cache_audioget[uid][key];
			var time = secondsToTime(val.duration);
			
			var new_key = tracks.length;
			tracks[new_key] = [val.url, val.artist, val.title, time.m+":"+str_pad(time.s, 2, '0', 'STR_PAD_LEFT'),val.owner_id+'_'+val.aid];
			tracktitle = val.artist + ' - ' + val.title;
			
			tmp+="<table class=track id='tracktracks"+new_key+"' onclick='load_track("+new_key+", \"manual\");'><tr><td class=position_tracks>"+(new_key*1+1)+"</td><td title='"+tracktitle+"' class=artist_tracks><div>"+val.artist+"</div></td><td class=track_tracks title='"+tracktitle+"'><div>"+val.title+"</div></td></tr></table>";
		}
		$("#tracklist").html(tmp);

	}else{
		$("#tracklist").html("<font color=red>У данного пользователя не загружено ни одной аудиозаписи.</font>");
	}
	make_shuffle();

	$('#content_tracks').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
	content_tracks_loaded = true;

	//load_track('first');
	lock = false;
}

function load_trends(){

	if (!(trendstracks.length > 0))
	{
		var dataString = '';
		$.ajax({
		type: "POST",
		url: "/ajax_load_trends.php",
		data: dataString,
		cache: false,
		beforeSend: function(html)
		{
			$("#trendstracklist").html("<div class=load_tracks><img src='/img/ajax_loader.gif' width=32 height=8></div>");	
		},
		success: function(html){
			$("#trendstracklist").html("");	

			var arr = explode('<br>', html);
			var tracktitle = '';
			for (var key in arr) {
				var val = arr[key];
				if (val.length > 0)
				{
					var arr2 = explode('|', val);					
					var artist = arr2[0];
					var track = arr2[1];
					var getaids = arr2[2];
					var trend = arr2[3];
					trendstracks[trendstracks.length] = [artist, track, getaids, trend]; 
				}
			}


			for (var key in trendstracks) {
				var val = trendstracks[key];
				tracktitle = val[0] + ' - ' + val[1];
				$("#trendstracklist").append(("<table class=track id='tracktrends"+key+"' onclick='load_track("+key+", \"manual\");'><tr><td class=position_trends>"+(key*1+1)+"</td><td class=trend_trends >+"+val[3]+"</td><td title='"+tracktitle+"' class=artist_trends><div>"+val[0]+"</div></td><td class=track_trends title='"+tracktitle+"'><div>"+val[1]+"</div></td></tr></table>"));
			}

			$('#content_trends').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
			set_trends_tracks();
		
		}
		});
	}else{
		set_trends_tracks();
	}

}

function set_trends_tracks(){
	tracks = [];
	
	for (var key in trendstracks) {
		var val = trendstracks[key];
		tracks[key] = ['', val[0], val[1], '', val[2]];
	}

	make_shuffle();

	//load_track('first');
	return;
}


//Функция открывает список чартов
function show_chartlist(){
	$("#topplaylist").hide();
	$("#topcontent").show();
}
function load_chart(chart_name, chart_title){
	$("#topcontent").hide();
	$("#topplaylist").show();

	top1000tracks = [];

	mode = mode + '_' + chart_name;

	$("#chart_title").html(chart_title);
	$("#toptracklist").html("");	
	$("#content_top").jScrollPane({shwArrows: false, scrollbarWidth: 8, arrowSize: 0});

	var dataString = 'chart_name='+chart_name;
	$.ajax({
	type: "POST",
	url: "/ajax_load_chart.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
		$("#toptracklist").html("<div class=load_tracks><img src='/img/ajax_loader.gif' width=32 height=8></div>");	
	},
	success: function(html){
		$("#toptracklist").html("");	
		var arr = explode('<br>', html);
		var tracktitle = '';

		for (var key in arr) {
			var val = arr[key];
			if (val.length > 0)
			{
				var arr2 = explode('|', val);					
				var artist = arr2[0];
				var track = arr2[1];
				var getaids = arr2[2];
				var rating_change = arr2[3];
				top1000tracks[top1000tracks.length] = [artist, track, getaids, rating_change]; 
			}
		}

		for (var key in top1000tracks) {
			var val = top1000tracks[key];
			
			var change = '';
			if (val[3] == 'new')
			{
				change = '<span class=rating_new>new!</span>';
			}else if(val[3] == 0){
				change = '<span class=rating_none>--</span>';
			}else if(val[3] > 0){
				change = '<span class=rating_up>↑ +'+val[3]+'</span>';
			}else{
				change = '<span class=rating_down>↓ '+val[3]+'</span>';
			}

			tracktitle = val[0] + ' - ' + val[1];
			$("#toptracklist").append(("<table class=track id='tracktop"+key+"' onclick='load_track("+key+",\"manual\");'><tr><td class=position_trends>"+(key*1+1)+"</td><td class=trend_trends >"+change+"</td><td title='"+tracktitle+"' class=artist_trends><div>"+val[0]+"</div></td><td class=track_trends title='"+tracktitle+"'><div>"+val[1]+"</div></td></tr></table>"));
		}
		set_chart_tracks();
			
		$('#content_top').jScrollPane({shwArrows: false, scrollbarWidth: 8, arrowSize: 0});
	}
	});
}

function set_chart_tracks(){
	tracks = [];

	for (var key in top1000tracks) {
		var val = top1000tracks[key];
		tracks[key] = ['', val[0], val[1], '', val[2]];
	}
	
	make_shuffle();

	return;
}


function load_track(track_id, action){
	previous_track = current_track;
	if (track_id == 'first'){
		if (repeat_mode){

		}else if (shuffle_mode)
		{
			current_track = tracks_shuffle[0];
		}else{
			current_track = 0;
		}
	}else if (track_id == 'next'){
		if (current_mode != mode)
		{
			if (repeat_mode && (action=='auto'))
			{
				if (action == 'manual')
				{
					current_track = 0;
				}
			}else if (shuffle_mode)
			{
				if (shuffle_position == (tracks.length-1)){
					shuffle_position = 0;
				}else{
					shuffle_position = shuffle_position*1+1;
				}

				current_track = tracks_shuffle[shuffle_position];
			}else{
				current_track = 0;
			}
		}else{
			if (repeat_mode && (action=='auto'))
			{

			}else if (shuffle_mode)
			{
				if (shuffle_position == (tracks.length-1)){
					shuffle_position = 0;
				}else{
					shuffle_position = shuffle_position*1+1;
				}

				current_track = tracks_shuffle[shuffle_position];
			}else{
				if (current_track == (tracks.length-1)){
					current_track = 0;
				}else{
					current_track = current_track+1;
				}
			}
		}
	}else if(track_id == 'prev'){
		if (current_mode != mode)
		{
			if (shuffle_mode)
			{
				if (shuffle_position == (tracks.length-1)){
					shuffle_position = 0;
				}else{
					shuffle_position = shuffle_position*1+1;
				}

				current_track = tracks_shuffle[shuffle_position];
			}else{
				current_track = tracks.length-1;
			}
		}else{
			if (shuffle_mode)
			{
				if (shuffle_position == 0){
					shuffle_position = tracks.length-1;
				}else{
					shuffle_position = shuffle_position-1;		
				}
				current_track = tracks_shuffle[shuffle_position];
			}else{
				if (current_track == 0){
					current_track = tracks.length-1;
				}else{
					current_track = current_track-1;		
				}
			}
		}
	}else{
		//если track_id - число, ставим этот трек на проигрывание
		current_track = track_id;
	}

	if (strpos(mode, 'top') !== false)
	{
		var modediv = 'top';
	}else{
		var modediv = mode;
	}

	if ((!repeat_mode) || (action == 'manual'))
	{
	
	$("#track"+modediv+current_track+"").removeClass("track_selected");
	$("#track"+modediv+previous_track+"").removeClass("track_selected");

	var play_track = current_track;
	current_mode = mode;

	$("#track"+modediv+play_track+"").addClass("track_selected");

	if (tracks.length){
	if (!tracks[play_track][0].length)
	{
		VK.api("audio.getById", {audios:tracks[play_track][4]}, function(data) {		
			if (data.response.length > 0)
			{
				tracks[play_track][0] = data.response[0].url;
				current_trackid = tracks[play_track][4];
				current_artist = tracks[play_track][1];
				current_title = tracks[play_track][2];

				$("#jquery_jplayer_2").jPlayer("setMedia", { mp3: tracks[play_track][0] });
				if (track_id != 'first')
				{
					$("#jquery_jplayer_2").jPlayer("play", 0);
				}
				$('.jp-track').html(tracks[play_track][2]);
				$('.jp-track').attr("title", tracks[play_track][2]);
				$('.jp-artist').html(tracks[play_track][1] + "<sup> <a href='#__JSNotWork' onclick='getArtistInfo();'><img src='/img/artist_info.png' width=10 height=10 title='info'></a></sup>");
				$('.jp-artist').attr("title", tracks[play_track][1]);

				//$("#savetrack").attr('href', 'http://www.google.com.ua/#q=cкачать mp3+'+tracks[play_track][1] + '+' +  tracks[play_track][2]);
				//$("#savetrack").attr('href', 'http://muzon.fm/?q='+tracks[play_track][1] + ' ' +  tracks[play_track][2]);
				$("#savetrack").attr('href', 'http://music.ardor.ru/search.php?p=1&v=0&q='+tracks[play_track][1] + ' ' +  tracks[play_track][2]);
				$("#savetrack").attr('target', '_blank');
			}else{
				VK.api("audio.search", {q:str_replace((tracks[play_track][1] + ' ' + tracks[play_track][2]), '&',''), count: 200}, function(data) {
					var ok = false;
					if(data.response[0] > 0){
						for (var key in data.response) {
							if (key>0)
							{
								ok = true;
								var val = data.response[key];
								if (shorttitle(tracks[play_track][1].toLowerCase()+tracks[play_track][2].toLowerCase()) != shorttitle(val.artist.toLowerCase()+val.title.toLowerCase())){
									ok = false;
								}

								if (ok)
								{

									tracks[play_track][0] = val.url;
									tracks[play_track][4] = val.owner_id+'_'+val.aid;
									current_artist = tracks[play_track][1];
									current_title = tracks[play_track][2];
									current_trackid = tracks[play_track][4];
									$("#jquery_jplayer_2").jPlayer("setMedia", { mp3: tracks[play_track][0] });
									if (track_id != 'first')
									{
										$("#jquery_jplayer_2").jPlayer("play", 0);
									}
									$('.jp-track').html(tracks[play_track][2]);
									$('.jp-track').attr("title", tracks[play_track][2]);
									$('.jp-artist').html(tracks[play_track][1] + "<sup> <a href='#__JSNotWork' onclick='getArtistInfo();'><img src='/img/artist_info.png' width=10 height=10 title='info'></a></sup>");
									$('.jp-artist').attr("title", tracks[play_track][1]);

									$("#savetrack").attr('href', 'http://music.ardor.ru/search.php?p=1&v=0&q='+tracks[play_track][1] + ' ' +  tracks[play_track][2]);
									$("#savetrack").attr('target', '_blank');
									break;
								}
							}
						}
					}
					if(!ok){
						load_track('next', 'manual');						
					}					
				});
			}
		});
	}else{

		$("#jquery_jplayer_2").jPlayer("setMedia", { mp3: tracks[play_track][0] });
		if (track_id != 'first')
		{
			$("#jquery_jplayer_2").jPlayer("play", 0);
		}
		$('.jp-track').html(tracks[play_track][2]);
		$('.jp-artist').html(tracks[play_track][1] + "<sup> <a href='#__JSNotWork' onclick='getArtistInfo();'><img src='/img/artist_info.png' width=10 height=10 title='info'></a></sup>");
		$('.jp-artist').attr("title", tracks[play_track][1]);
		$('.jp-track').attr("title", tracks[play_track][2]);

		current_trackid = tracks[play_track][4];
		current_artist = tracks[play_track][1];
		current_title = tracks[play_track][2];

		$("#savetrack").attr('href', 'http://music.ardor.ru/search.php?p=1&v=0&q='+tracks[play_track][1] + ' ' +  tracks[play_track][2]);
		$("#savetrack").attr('target', '_blank');
	}
	}
	//Скроллинг к текущей композиции

		var row_height = 17;
		$('#content_'+modediv)[0].scrollTo(row_height*current_track - 9*row_height);
		//Убрать галочку с кнопки "нравится"
		$("#liketrack").removeClass('liketrack_done');
		$("#liketrack").addClass('liketrack');
		$("#disliketrack").removeClass('disliketrack_done');
		$("#disliketrack").addClass('disliketrack');
	}else{
		$("#jquery_jplayer_2").jPlayer("play", 0);
	}
}

function sName(i, ii) { // По имени (возрастание)
    if (i[1].toLowerCase() > ii[1].toLowerCase())
        return 1;
    else if (i[1].toLowerCase() < ii[1].toLowerCase())
        return -1;
    else
        return 0;
}


function make_shuffle(){

	var tmp = Array();
	for (i=0;i<=(tracks.length-1);i++)
	{
		tmp[i] = i;
	}
	var length = tmp.length;
	tracks_shuffle = [];
	while (length > 0){
		var rand = Math.floor(Math.random()*length);
		tracks_shuffle[tracks_shuffle.length]=tmp[rand];
		tmp[rand]=tmp[length-1];
		delete tmp[length-1];
		length = length - 1;
	}
	return;
}

function toggle_shuffle(){
	if (!shuffle_mode){

		$("#shuffle").removeClass('shuffle');
		$("#shuffle").addClass('shuffle_a');
		make_shuffle();
		shuffle_mode = true;
	}else{
		$("#shuffle").removeClass('shuffle_a');
		$("#shuffle").addClass('shuffle');
		shuffle_mode = false;
	}
}

function toggle_repeat(){
	if (!repeat_mode){
		$("#repeat").removeClass('repeat');
		$("#repeat").addClass('repeat_a');
		repeat_mode = true;
	}else{
		$("#repeat").removeClass('repeat_a');
		$("#repeat").addClass('repeat');
		repeat_mode = false;
	}
}



function add_current_track(){
	if (current_trackid.length > 0)
	{
		msgbox_show("<div style='height: 12px;'><img src='/img/loader.gif' width=149 height=8 style='margin-top: 2px;'></div>", '205px');

		var tmp = explode('_', current_trackid);
		var oid = tmp[0];
		var aid = tmp[1];

		VK.api("audio.add", {aid:aid, oid:oid}, function(data) {
			if(data.response == 1){
				msgbox_show("<div style='height: 12px;'>Добавление прошло успешно!</div>", '205px');

				delete cache_audioget[viewer_id];

			}else{
				msgbox_show("<div style='height: 12px;'>Произошла ошибка (#"+data.error+")</div>", '205px');
			}
		});	
	}else{
		msgbox_show("Аудиозапись не выбрана");
	}
}

function like_current_track(){
	if (current_trackid.length > 0)
	{

		var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&track='+encodeURIComponent(current_artist+current_title);
		$.ajax({
		type: "POST",
		url: "/ajax_like.php",
		data: dataString,
		cache: false,
		beforeSend: function(html)
		{

		},
		success: function(html){
			$("#liketrack").removeClass('liketrack');
			$("#liketrack").addClass('liketrack_done');
			msgbox_show("Голос учтен!", 'auto');
		}
		});

	}else{
		msgbox_show("Аудиозапись не выбрана", 'auto');
	}
}

function dislike_current_track(){
	if (current_trackid.length > 0)
	{

		var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&track='+encodeURIComponent(current_artist+current_title);
		$.ajax({
		type: "POST",
		url: "/ajax_like.php?mode=dislike",
		data: dataString,
		cache: false,
		beforeSend: function(html)
		{

		},
		success: function(html){
			$("#disliketrack").removeClass('disliketrack');
			$("#disliketrack").addClass('disliketrack_done');
			msgbox_show("Голос учтен!", 'auto');
		}
		});

	}else{
		msgbox_show("Аудиозапись не выбрана", 'auto');
	}
}

function msgbox_show(message, width, type){
  if ($("#msgbox").css("left") == '0px')
  {
	msgbox_hide();
  }

  if (width === undefined){
    width = 'auto';
  }
  if (type === undefined){
    type = 'message';
  }

  if (type == 'addtrack'){
	$("#msg_addtrack").show();
  }else if(type == 'artist_info'){
	$("#msg_artist_info").show();
  }else if(type == 'help'){
	$("#msg_help").show();
  }else if(type == 'delete'){
	$("#msg_delete").show();
  }else{
	$("#msg_message_text").html(message);
	$("#msg_message").show();
  }

	$("#msgbox_table").css("width", width);
	$("#msgbox").css("left", "0px");
}

function msgbox_hide(){
	$("#msg_message").hide();
	$("#msg_addtrack").hide();
	$("#msg_help").hide();
	$("#msg_delete").hide();
	$("#msg_artist_info").hide();
	$("#msgbox").css("left", "-1000px");
}

function add_banner(){
	VK.api("wall.savePost", {wall_id:viewer_id, photo_id: "6491374_210284898", message:"Меломания → новый аудиоплеер в Контакте. Персональное радио. Плеер музыки со страниц друзей. Самая популярная музыка Контакта. Отслеживание музыкальных тенденций. Поиск людей со схожими плейлистами. ____________________________________________________ Установить: http://vkontakte.ru/app2113983" }, function(data) {
		VK.callMethod("saveWallPost", data.response.post_hash);  
	});
}

// Быстрые клавиши
document.onkeydown = NavigateThrough;
function NavigateThrough (event)
    {
    if (!document.getElementById) return;
    if (window.event) event = window.event;
	if (event.ctrlKey)
	    {
		var link = null;
		var href = null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
		    {
			case 0x25:
				load_track('prev','manual');
				break;
			case 0x27:
				load_track('next','manual');
				break;
			case 0x26:
				var tmp = volume+0.1;
				if (tmp > 1)
				{
					tmp = 1;
				}
				$("#jquery_jplayer_2").jPlayer("volume", tmp);
				break;
			case 0x28:
				var tmp = volume-0.1;
				if (tmp < 0)
				{
					tmp = 0;
				}
				$("#jquery_jplayer_2").jPlayer("volume", tmp);
				break;
    }
	}
	}

function getArtistInfo(){

	msgbox_show('','', 'artist_info');
	$.ajax({
	type: "GET",
	url: "/ajax_artist_info.php?artist="+encodeURIComponent(tracks[current_track][1]),
	cache: false,
	beforeSend: function(html)
	{
		$("#artist_info_content").html("<img src='/img/loader.gif' width=149 height=8 style='margin-top: 2px;'>");
	},
	success: function(html){
		$("#artist_info_content").html(html);
	}
	});
}

function showhelp(){
	$.ajax({
	type: "GET",
	url: "/help.html",
	cache: false,
	beforeSend: function(html)
	{
		$("#help_content").html("<img src='/img/loader.gif' width=149 height=8 style='margin-top: 2px;'>");
	},
	success: function(html){
		$("#help_content").html(html);
	}
	});
	msgbox_show('','', 'help');
}

function shorttitle(str){
	str = str_replace(str, '&amp;', '&');
	str = translit2(str);
	str = str.toLowerCase();
	str = str.replace(/[^a-z0-9]/gi,"");
	return str;
}



function search_music(mode){

	var searchartist = trimSpaces(trimBoth(str_replace($("#searchartist").val(), ' & ', ' ')));
	var searchartist_arr = explode(' ', searchartist);
	for (var key2 in searchartist_arr) {
		searchartist_arr[key2] = htmlentities(searchartist_arr[key2]);
	}

	var searchtrack =  trimSpaces(trimBoth(str_replace($("#searchtrack").val(), ' & ', ' ')));
	var searchtrack_arr = explode(' ', searchtrack);
	for (var key2 in searchtrack_arr) {
		searchtrack_arr[key2] = htmlentities(searchtrack_arr[key2]);
	}

	var searchunique = $("#searchunique").attr('checked');
	if (searchartist == 'Исполнитель')
	{
		searchartist = '';
	}
	if (searchtrack == 'Композиция')
	{
		searchtrack = '';
	}

	if (content_search_loaded){
		if ($("#searchtracklist").height()>340){
			$('#content_search')[0].scrollTo(0);
		};
	}	

	if ((searchartist.length > 0) || (searchtrack.length > 0))
	{

	$('#search_more').html("<img src='/img/ajax_loader.gif' width=32 height=8 vspace=7>");

	var shortquery = shorttitle(searchartist + searchtrack);

	if (mode == 'new')
	{
		searchparams = [];
	}

	if (searchparams[shortquery] === undefined)
	{
		searchparams[shortquery] = 0;
	}

	VK.api("audio.search", {q:(searchartist+ ' ' +searchtrack), count: 200, offset: searchparams[shortquery]}, function(data) {

		if (mode == 'new'){
			searchtracks = [];
			tracks = [];
			$("#searchtracklist").html('');
			$('#content_search').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
		}
		
		searchparams[shortquery] = searchparams[shortquery] + 200;

		var tracktitle = '';
		var tmp = $("#searchtracklist").html();
		var ok = '';
		var shortt = '';

		if(data.response[0] > 0){
			for (var key in data.response) {
				if (key>0)
				{
					ok = true;
					var val = data.response[key];

					//проверки
					if (searchunique)
					{
						if (searchartist.length > 0){
							if (htmlentities(searchartist.toLowerCase()) != val.artist.toLowerCase())
							{
								ok = false;
							}
						}
						if (searchtrack.length > 0){
							if (htmlentities(searchtrack.toLowerCase()) != val.title.toLowerCase())
							{
								ok = false;
							}
						}
					}else{
						if (searchartist.length > 0){
							for (var key2 in searchartist_arr) {
								var val2 = searchartist_arr[key2].toLowerCase();
								if ((strpos(val.artist.toLowerCase(), val2,0) === false) && (val2.length > 2))
								{
									ok = false;
								}
							}
						}
						if (searchtrack.length > 0){
							for (var key2 in searchtrack_arr) {
								var val2 = searchtrack_arr[key2].toLowerCase();
								if ((strpos(val.title.toLowerCase(), val2,0) === false) && (val2.length > 2))
								{
									ok = false;
								}
							}
						}
					}

					shortt = shorttitle(val.artist + val.title);					

					if (in_array(shortt, searchtracks))
					{
						ok = false;
					}

					if (ok)
					{
						searchtracks[searchtracks.length] = shortt;

						var new_key = tracks.length;

						tracks[new_key] = [val.url, val.artist, val.title, '',val.owner_id+'_'+val.aid];
						tracktitle = val.artist + ' - ' + val.title;

						tmp+="<table class=track id='tracksearch"+new_key+"' onclick='load_track("+new_key+", \"manual\");'><tr><td class=position_search>"+(new_key*1+1)+"</td><td title='"+tracktitle+"' class=artist_search><div>"+val.artist+"</div></td><td class=track_search title='"+tracktitle+"'><div>"+val.title+"</div></td></tr></table>";
					}
				}
			}
			
			make_shuffle();
			$("#searchtracklist").html(tmp);			
			$('#search_more').html("<table class='button_blue button_blue_small'><tr><td ><a href='javascript: void(0)' onclick='search_music(\"more\");' style='padding-left: 17px; padding-right: 17px'>Еще!</a></td></tr></table>");
			$('#content_search').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
			content_search_loaded = true;

			$('.button_blue').bind('mouseenter', function(event) {
				$(this).fadeTo('fast', '0.8');
			});
			$('.button_blue').bind('mouseleave', function(event) {
				$(this).fadeTo('fast', '1');
			});
		}else{
			$('#searchtracklist').html("");	
			$('#search_more').html("");
			$('#content_search').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
			content_search_loaded = true;			
		}
		
	});	
	}else{
		msgbox_show("Параметры поиска не заданы");
	}
}

function add_artistlist(){
	var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&action=add_artistlist';
	$.ajax({
	type: "POST",
	url: "/ajax_artistlist.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
		$("#artistlist_list").html("<img src='/img/ajax_loader.gif' width=32 height=8>");
	},
	success: function(html){
		load_artistlist();
		gen_artistlist();
		//$("#artistlist_list").html('ok');
	}
	});
}

function load_artistlist(){
	$("#artistlist_list").html("<img src='/img/ajax_loader.gif' width=32 height=8>");

	var dataString = 'gendj='+gendj+'&viewer_id='+ viewer_id + '&sig='+sig+'&action=load_artistlist';
	gendj = 1;
	$.ajax({
	type: "POST",
	url: "/ajax_artistlist.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
		
	},
	success: function(html){
		artistlist = [];
		var arr = explode('<br>', html);
		for (var key in arr) {
			var val = arr[key];
			if (val.length > 0)
			{
				var arr2 = explode('|', val);					
				var artistlist_id = arr2[0];
				var title = arr2[1];
				artistlist[artistlist.length] = [artistlist_id, title]; 
			}
		}
		gen_artistlist();
	}
	});
}

function gen_artistlist(){
	$("#select_artistlist_list").empty();
	if (artistlist.length > 0)
	{
		var tmp = '';
		for (var key in artistlist) {
			var val = artistlist[key];
			var artistlist_id = val[0];
			var title = val[1];
			tmp += "<table class=track id='trackradio"+artistlist_id+"'><tr><td class=listtitle_tracks onclick='load_dj("+artistlist_id+");'><div>"+str_replace(title, '<','&lt;')+"</div></td><td class=listedit_tracks><div onclick='edit_tracklist("+key+")'><img src='/img/edit.gif' width=10 height=10 style='vertical-align: absmiddle;'> редактировать</div></td></tr></table>";
			$("#select_artistlist_list").append( $('<option value="'+artistlist_id+'">'+str_replace(title, '<','&lt;')+'</option>') );
		}
		$("#artistlist_list").html(tmp);
	}else{
		$("#artistlist_list").html('<font color=gray>У вас пока нет ни одного списка исполнителей...<br>Нажмите кнопку "Добавить" и отредактируйте новый список - введите название, и перечислите исполнителей, которые вам нравятся.</font>');
	}
	$('#artistlist_list_scroll').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
}

function edit_tracklist(key){
	$("#edit_tracklist").hide();
	$("#edit_tracklist_div").show();

	$("#artistlist_title").val(artistlist[key][1]);
	$("#artistlist_id").val(artistlist[key][0]);
	
	for (var key2 in artistlist) {
		$("#trackradio"+artistlist[key2][0]).removeClass("track_selected");
	}
	$("#trackradio"+artistlist[key][0]).addClass("track_selected");
	load_artists();
}

function load_artists(){
	$("#artist_list").html("<img src='/img/ajax_loader.gif' width=32 height=8 vspace=7>");
	var artistlist_id =  $("#artistlist_id").val();
	var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&action=load_artists&artistlist_id='+artistlist_id;
	$.ajax({
	type: "POST",
	url: "/ajax_artistlist.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
	},
	success: function(html){
		$("#artist_list").html(html);
		$('#artist_list_scroll').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
	}
	});
}

function delete_artistlist(){
	$("#artistlist_list").html("<img src='/img/ajax_loader.gif' width=32 height=8>");
	var artistlist_id =  $("#artistlist_id").val();
	var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&action=delete_artistlist&artistlist_id='+artistlist_id;
	$.ajax({
	type: "POST",
	url: "/ajax_artistlist.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
		hide_editform();
		$("#edit_tracklist").html("<img src='/img/ajax_loader.gif' width=32 height=8 vspace=15>");
	},
	success: function(html){
		load_artistlist();
		$("#edit_tracklist").html("&nbsp;");
	}
	});
}

function save_artistlist(){

	var tmp = [], el;
	for(i=0; el = document.forms.artistlist.elements[i] ; i++){
		el.value = str_replace(el.value, '|','');
		el.value = str_replace(el.value, '<br>','');
		el.value = str_replace(el.value, '{','');
		el.value = str_replace(el.value, '}','');
		if (el.type == 'checkbox')
		{
			if (el.checked)
			{
				tmp.push(el.id + '=' + encodeURIComponent(el.value));
			}
		}else{
			tmp.push(el.id + '=' + encodeURIComponent(el.value));
		}
	}
	var str = tmp.join("&");

	//var artistlist_id =  $("#artistlist_id").val();
	//var artistlist_title =  $("#artistlist_title").val();
	var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&action=save_artistlist&'+str;
	$.ajax({
	type: "POST",
	url: "/ajax_artistlist.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
		hide_editform();
		$("#edit_tracklist").html("<img src='/img/ajax_loader.gif' width=32 height=8 vspace=15>");
	},
	success: function(html){
		load_artistlist();
		$("#edit_tracklist").html("&nbsp;");
	}
	});
}

function hide_editform(){
		$("#artistlist_id").val('');
		$("#edit_tracklist_div").hide();
		$("#edit_tracklist").show();
}
function hide_djtracks(){
	$("#dj_loader").hide();
	$("#dj_tracks").hide();		
	$("#dj_edit").show();
}
function add_artist(){
	var tmp = Math.round(Math.random() * 100000);
	$("#artist_list").append("<div style='margin-top: 2px; font-size: 7pt; color: gray;' id='new_artist_div_"+tmp+"'><a href='javascript: void(0)' onclick='delete_new_artist("+tmp+")'><img src='/img/delete.png' title='Удалить исполнителя' width=10 height=10 hspace=3 style='padding-top: 3px;'></a><input type=text id='new_artist_title_"+tmp+"' value='' style='width: 120px; border: 1px solid gray; padding: 2px; font-size: 8pt;' maxlength=40 ><input id='new_artist_check_"+tmp+"' type=checkbox checked value='on' title='При формировании плейлиста искать похожих исполнителей'> похожее</div>");
	$('#artist_list_scroll').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
	$('#artist_list_scroll')[0].scrollTo(99999999999);
}

function delete_new_artist(id){
	$("#new_artist_title_"+id).val('');
	$("#new_artist_div_"+id).fadeOut();
	$('#artist_list_scroll').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
}
function delete_artist(id){
	$("#artist_title_"+id).val('');
	$("#artist_div_"+id).fadeOut();
	$('#artist_list_scroll').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
}

function load_dj(artistlist_id){

	stop_loading_dj = false;
	$("#select_artistlist_list [value='"+artistlist_id+"']").attr("selected", "selected");
	$("#dj_edit").hide();
	$("#dj_tracks").hide();
	$("#dj_loader").show();
	$("#dj_loader_a").css('background-position', '0px top');
	tracks = [];
	searchtracks = [];

	var dataString = 'viewer_id='+ viewer_id + '&sig='+sig+'&action=load_dj&artistlist_id='+artistlist_id;
	$.ajax({
	type: "POST",
	url: "/ajax_artistlist.php",
	data: dataString,
	cache: false,
	beforeSend: function(html)
	{
		
	},
	success: function(html){
		var arr = explode('|', html);
		if (arr[1] !== undefined)
		{
			search_dj(html, 0, 0);
		}else{
			search_dj(html, 0, 1);
		}

	}
	});

}
//SELECT *  FROM `tracks` WHERE (MATCH (`artist`) AGAINST ('chemical')) AND (MATCH (`artist`) AGAINST ('brothers')) ORDER BY `change` DESC

var searchtracks_short = new Array();
function search_dj(html, key_new, is_last){

	var arr = explode('|', html);
	var count = 440  - arr.length*40;
	if (count < 20)
	{
		count = 40;
	}
	
	$("#dj_preloader").html((key_new+1)+ ' из ' + arr.length);
	
	$("#dj_loader_a").css('background-position', Math.floor(300*(key_new+1)/arr.length)+'px top');
	

	VK.api("audio.search", {q:arr[key_new], count: count,offset: (Math.floor(Math.random()*900))}, function(data) {
	var tracktitle = '';
	var ok = '';
	var shortt = '';

	var searchartist_arr = explode(' ', arr[key_new]);
	for (var key2 in searchartist_arr) {
		searchartist_arr[key2] = htmlentities(searchartist_arr[key2]);
	}
	if(data.response[0] > 1000){
		for (var key in data.response) {
			if (key>0)
			{
				ok = true;
				var val = data.response[key];

				for (var key2 in searchartist_arr) {
					var val2 = searchartist_arr[key2].toLowerCase();
					if ((strpos(' '+val.artist.toLowerCase()+' ', ' '+val2+' ',0) === false) && (val2.length > 2))
					{
						ok = false;
					}
				}

				shortt = shorttitle(val.artist + val.title);					

				if (in_array(shortt, searchtracks_short))
				{
					ok = false;
				}

				if (ok)
				{
					searchtracks_short[searchtracks.length] = shortt;

					var new_key = searchtracks.length;

					searchtracks[new_key] = [val.url, val.artist, val.title, '',val.owner_id+'_'+val.aid];
					tracktitle = val.artist + ' - ' + val.title;
				}
			}
		}	
	}
	if (is_last == '1')
	{	
		$("#dj_loader").hide();
		$("#dj_tracks").show();			
		var len = 0;
		var length = searchtracks.length;
		while ((len < 100) && (length > 0)){
			var rand = Math.floor(Math.random()*length);
			tracks[tracks.length]=searchtracks[rand];
			searchtracks[rand]=searchtracks[length-1];
			delete searchtracks[length-1];
			len++;
			length--;
		}
		if (tracks.length > 0)
		{
			var tmp = '';
			for (var key in tracks) {
				tracktitle = tracks[key][1] + ' - ' + tracks[key][2];
				tmp+="<table class=track id='trackdj"+key+"' onclick='load_track("+key+", \"manual\");'><tr><td class=position_search>"+(key*1+1)+"</td><td title='"+tracktitle+"' class=artist_search><div>"+tracks[key][1]+"</div></td><td class=track_search title='"+tracktitle+"'><div>"+tracks[key][2]+"</div></td></tr></table>";
			}

		}else{
			tmp = "<div style='color: gray;'>По вашему запросу ничего не найдено.</div>";
		}
	
		make_shuffle();
		$("#djtracklist").html(tmp);

		$('#content_dj').jScrollPane({showArrows: false, scrollbarWidth: 8, arrowSize: 0});
		$('#content_dj')[0].scrollTo(0);

	}


	});

	if (arr[key_new+1]!==undefined)
	{
		if (arr[key_new+2]!==undefined)
		{
			var last = '0';
		}else{
			var last = '1';
		}
		if (!stop_loading_dj)
		{
			setTimeout('search_dj("'+str_replace(html, '"',"\\\"")+'", '+(key_new+1)+', '+last+');', 1000);
		}
	}
	return;
}